<?php
/**
 * Library for easier record list manipulation.
 *
 * @author Martin "DevelX" Jurča
 * @version 2009-02-24
 */
class RecordList {
    /**
     * The DataBase API object.
     *
     * @var DBAPI DataBase API.
     */
    private $dbapi;

    public function __construct(DBAPI $dbapi) {
        if ($dbapi == null) {
            throw new Exception("DBAPI cannot be null");
        }
        $this->dbapi = $dbapi;
    }

    public function &getList($dataModel, &$parameters) {
        $count = isset($parameters['count']) ? $parameters['count'] : 65565;
        $start = isset($parameters['start']) ? $parameters['start'] : 0;
        $order = isset($parameters['order']) ? $parameters['order'] : array();
        $filter = isset($parameters['filter']) ? $parameters['filter'] : '';
        $items = array();
        $records = $this->dbapi->load($dataModel, $filter, $order, $start,
                $count);
        $filterProperties = isset($parameters['properties']) &&
                is_array($parameters['properties']);
        foreach ($records as $record) {
            if ($filterProperties) {
                $items[] = &$this->filterProperties($record,
                        $parameters['properties']);
            } else {
                $items[] = $record['data'];
            }
        }
        return $items;
    }

    /**
     * Filters properties of record.
     *
     * @param Array $record Record.
     * @param Array $properties List of properties to return.
     * @return Array Filtered properties of record.
     */
    private function &filterProperties(&$record, &$properties) {
        $item = array();
        foreach ($properties as $property) {
            if (isset($record['data'][$property])) {
                $item[$property] = $record['data'][$property];
            } else {
                $item[$property] = null;
            }
        }
        return $item;
    }
}
?>
